<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ include file="/jsp/common/common.jsp"%>  
<html>
	<head>
		<base target="_self" />
		<meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <title></title>
		<link rel="stylesheet" type="text/css" href="<c:url value="/static/jquery-easyui/themes/default/easyui.css"/>">
		<link rel="stylesheet" type="text/css"
			href="<c:url value="/static/jquery-easyui/themes/icon.css"/>">
		<script type="text/javascript"
			src="<c:url value="/static/jquery-easyui/jquery-1.6.min.js"/>"></script>
		<script type="text/javascript"
			src="<c:url value="/static/jquery-easyui/jquery.easyui.min.js"/>"></script>
		<script type="text/javascript"
			src="<c:url value="/static/jquery-easyui/plugins/jquery.panel.js"/>"></script>
		<script type="text/javascript"
			src="<c:url value="/static/jquery-easyui/plugins/jquery.datagrid.js"/>"></script>
		<script type="text/javascript"
			src="<c:url value="/static/jquery-easyui/plugins/jquery.messager.js"/>"></script>
		<script type="text/javascript"
			src="<c:url value="/static/js/json2.js"/>"></script>
		<script type="text/javascript"
			src="<c:url value="/static/jquery-easyui/ext-for-framework.js.jsp"/>"></script>
		<script type="text/javascript" src="<c:url value="/static/jquery-easyui/locale/easyui-lang-zh_CN.js"/>"></script>
		<script type="text/javascript"
			src="<c:url value="/static/js/common.js"/>"></script>		
		<script type="text/javascript">
		    var map = {}; // Map map = new HashMap();
		    var selectMap = {};//材料是否被选择map
		
		    function initList2(listDisplayEId) {
                $('#' + listDisplayEId).datagrid(
                        {
                            nowrap : false,
                            striped : true,
                            collapsible : true,
                            remoteSort : true,
                            notSelectByRow : false,
                            onCheck:function(rowIndex,rowData){
                            }
                        });
                
            };
			function initList(listDisplayEId) {
				$('#' + listDisplayEId).datagrid(
						{
							nowrap : false,
							striped : true,
							collapsible : true,
							remoteSort : true,
							notSelectByRow : false,
							
							toolbar : [
									
									{
										id : listDisplayEId + '_btn_edit',
										text : '出库',
										iconCls : 'icon-edit',
										handler : function() {	
											
											var rows = $('#'+listDisplayEId).datagrid('getSelections');	
											for(var i=0; i<rows.length; i++){
											    var rowIndex=$('#'+listDisplayEId).datagrid('getRowIndex',rows[i]['sid']);
												$('#listDisplay').datagrid('endEdit', rowIndex);
											}
											var row = $('#'+listDisplayEId).datagrid('getSelections');	
											if(row.length == 0){
												$.messager.alert('提示','请选择一条记录操作！','info');
												return;
											}else{
												var userList = new Array(); 
												var jsonFater;
												for (var i = 0 ; i < row.length;i++){
													
													if ( row[i]['materNumOut'] == "" || !isNumberAndNoZero(row[i]['materNumOut'])  ){
														alert("材料"+row[i]['materName']+"，出库数量请填写数字！");
														return false;
													}
													//判断库存数量和出库数量 
													var storeNumber = row[i]['materNum']-0;
												    var minStoreNumber = row[i]['materNumOut']-0;
												    if(!isNaN(storeNumber)&&!isNaN(minStoreNumber)){
												    	if(storeNumber<minStoreNumber){
												    		$.messager.alert('提示','材料（'+row[i]['materName']+'），出库数量不能大于库存数量','info');
	                                                        return;
												    	}
												    }else{
												    	$.messager.alert('提示','出库数量请填入数字','info');
		                                                return;
												    }
												    
													
													
													var  jsonSun = "{materId:'"+row[i]['materId']+"',materNumOut:'"+row[i]['materNumOut']+"'}";
													userList.push(jsonSun);
												}
												jsonFater = JSON.stringify(userList);
												var str = "json="+jsonFater;	
												document.getElementsByName("materdategridList")[0].value = jsonFater;
												$.messager.confirm('提示', '是否提交记录？', function(r){
													//方法函数 进入后台
													if(r){
		                                                  addStore();
													}
													
												});
											}
										}
									}],
							onLoadError:function(){
								$.messager.alert('错误','获取数据失败，请与管理员联系！','error');
							}
						    ,onClickRow:function(rowIndex){
                                $(".myrad").prop("checked",false);
                                $(".myrad").eq(rowIndex).prop("checked",true);
                                $('#listDisplay').datagrid('beginEdit', rowIndex);
                            }
						    ,onCheck:function(rowIndex,rowData){
                                selectMap[rowData['sid']]=1;
                                $('#listDisplay2').datagrid('appendRow',{
                                	sid:rowData['sid'],
                                    materId:rowData['materId'],
                                    materName:rowData['materName'],
                                    materType:rowData['materType'],
                                    unit:rowData['unit'],
                                    brands:rowData['brands'],
                                    materNum:rowData['materNum'],
                                    materNumOut:rowData['materNumOut'],
                                    specifications:rowData['specifications']
                                }); 
                            }
                            ,onUncheck:function(rowIndex,rowData){
                                delete selectMap[rowData['sid']];
                                var deleteIndex = $('#listDisplay2').datagrid('getRowIndex', rowData['sid']);
                                if(deleteIndex!=-1){
                                    $('#listDisplay2').datagrid('deleteRow',deleteIndex); 
                                }
                            }
                            ,onCheckAll:function(rows){
                                for(var i=0;i<rows.length;i++){
                                    var table2Index = $('#listDisplay2').datagrid('getRowIndex',rows[i]['sid']);
                                    if(table2Index == -1){
                                        $('#listDisplay2').datagrid('appendRow',{
                                            sid:rows[i]['sid'],
                                            materId:rows[i]['materId'],
                                            materName:rows[i]['materName'],
                                            materType:rows[i]['materType'],
                                            materNum:rows[i]['materNum'],
                                            materNumOut:rows[i]['materNumOut'],
                                            unit:rows[i]['unit'],
                                            brands:rows[i]['brands'],
                                            specifications:rows[i]['specifications']
                                        }); 
                                    }
                                    
                                }
                            }
                            ,onUncheckAll:function(rows){
                                for(var i=0;i<rows.length;i++){
                                    var deleteIndex = $('#listDisplay2').datagrid('getRowIndex', rows[i]['sid']);
                                    $('#listDisplay2').datagrid('deleteRow',deleteIndex);
                                }
                            },
                            onLoadSuccess:function(){ 
                                //初始化 复选框
                                var allrows = $('#listDisplay').datagrid("getRows");
                                for (var i = 0; i < allrows.length; i++) {
                                    var rowIndex = $('#listDisplay').datagrid('getRowIndex', allrows[i]['sid']);
                                    var hasSelect = allrows[i]['sid'] in selectMap;
                                    if(hasSelect){
                                       //$('#listDisplay').datagrid("checkRow",rowIndex);
                                    } else {
                                        var allRowsChecked = $("#listDisplay").datagrid('getChecked');
                                        for (var j = 0; j < allRowsChecked.length; j++) {
                                            if( allrows[i]['sid']==allRowsChecked[j]['sid']){
                                                $('#listDisplay').datagrid("uncheckRow",rowIndex);
                                            }
                                        }
                                    }
                                } 
                                //初始化数量
                                var rows = $('#'+listDisplayEId).datagrid('getRows');   
                                if(rows.length > 0){
                                    for (var i = 0 ; i < rows.length;i++){
                                        var key = rows[i]['sid'];
                                        var has = key in map; 
                                        if(has){
                                            rows[i]['materNumOut'] = map[key];
                                            $('#listDisplay').datagrid('refreshRow', i);
                                        }
                                    }
                                }
                            
                                $(".datagrid-row").mouseover(function(e){  
                                    if(checkHover(e,this)){
                                        var foodId = $(this).find('td').eq(1).text();
                                        var index = $('#listDisplay').datagrid('getRowIndex', foodId);
                                        $('#listDisplay').datagrid('beginEdit',index);
                                    }
                                }); 
                                $(".datagrid-row").mouseout(function(e){  
                                    if(checkHover(e,this)){
                                        var foodId2 = $(this).find('td').eq(1).text();
                                        var index2 = $('#listDisplay').datagrid('getRowIndex', foodId2);
                                        $('#listDisplay').datagrid('endEdit',index2);
                                        if( $(this).find('td').eq(9).text()!=''){
                                            map[$(this).find('td').eq(1).text()] = $(this).find('td').eq(9).text(); 
                                            //已选材料设置------start
                                            var table2Index = $('#listDisplay2').datagrid('getRowIndex',$(this).find('td').eq(1).text());
                                            if(table2Index != -1){
                                                var rowDateTable2 = $('#listDisplay2').datagrid('getRows', table2Index);
                                                for (var m = 0 ; m < rowDateTable2.length;m++){
                                                    if(rowDateTable2[m]['sid']==$(this).find('td').eq(1).text()){
                                                       rowDateTable2[m]['materNumOut']=$(this).find('td').eq(9).text();
                                                       $('#listDisplay2').datagrid('refreshRow', table2Index);
                                                    }
                                                }
                                            }
                                            //已选材料设置------end
                                        }else{
                                            //已选材料设置------start
                                            var table2Index = $('#listDisplay2').datagrid('getRowIndex',$(this).find('td').eq(1).text());
                                            if(table2Index != -1){
                                                var rowDateTable2 = $('#listDisplay2').datagrid('getRows', table2Index);
                                                for (var m = 0 ; m < rowDateTable2.length;m++){
                                                    if(rowDateTable2[m]['sid']==$(this).find('td').eq(1).text()){
                                                       rowDateTable2[m]['materNumOut']="";
                                                       $('#listDisplay2').datagrid('refreshRow', table2Index);
                                                    }
                                                }
                                            }
                                            //已选材料设置------end
                                            delete map[$(this).find('td').eq(1).text()];
                                        }
                                        
                                        
                                    }
                                });
                            } 
						});
				
			};
			$(document).ready(function() {
                initList2('listDisplay2');
				initList('listDisplay');
			});
			
 			function addStore(){
 	 			$('#AddStoreForm').form('submit',
 				{
 					url:'<c:url value='/store/minStore.do'/>', //查询提交路径
 					onSubmit:function()//提交按钮相应函数
 					{
 						return $('#AddStoreForm').form('validate');
 					},
 					success:function(data){
 						data = eval( "("+data+")" );
 		       			if(data.success){
 		       				$.messager.alert("提示", "提交成功！", 'info');
 	       				}else{
 	       					if(data.msg ='msg001'){
 	                            $.messager.alert("提示", '该库存存在未确认订单，请先确认完再执行新的出库任务。', 'warning');
 	       					}else{
 	                            $.messager.alert("提示", data.msg, 'warning');
 	       					}
 	       				}
 		       		    $('#listDisplay').datagrid('reload');
					    $('#listDisplay').datagrid('clearSelections');
 					},
 					error:function(){
 						$.messager.alert("错误", "系统错误，请联系管理员！", 'error');
 						return;
 					}
 				});
 	 			
 			}
 			
 			
 			function searchInfo(){
 				$('#listDisplay').datagrid('load', {
 				materName : $('#materName').val()
 				//,materType : $('#materType').val()
 				});  
 			}
 			
		</script>
			</head>
			<body>
			<table width="98%">
			<tr><td>
						<form id="AddStoreForm" name="AddStoreForm" method="post">
			
			<div style="height: auto; width:1180px;background: #fafafa; padding: 2px;" class="easyui-panel" title="&nbsp&nbsp&nbsp&nbsp&nbsp必录信息"  collapsible="true" minimizable="false" maximizable="false" closable="false">
			   <table cellpadding="5">
                  <tr>
                  	<td>出库用途</td>
                    <td>
 			            <input class="easyui-textbox" name="remark" id="remark" editable="true" data-options="multiline:true,required:true" style="height:60px;width:300px" /> 
 			        </td>
                  </tr>
                  <tr>
                    <td>
				        <input class="easyui-validatebox" type="hidden" name="materdategridList"  />
 			        </td>
                  </tr>
               </table>
             </div>
             </form>
           </td></tr>
           <tr>
			<td>
				<div style="height: auto; width:1180px;background: #fafafa; padding: 5px;" class="easyui-panel" title="查询" iconCls="icon-search" collapsible="true" minimizable="false" maximizable="false" closable="false">
					<form id="searchForm" name="searchForm" method="post"
						action="userlist.txt"
						onsubmit="return searchDGData(this.id,'listDisplay');">
						<div>
		            
		                                                           材料名：
							<input type="text" id="materName" name="materName"></input>
		                    <!--                        
		                                                          种类：
							<input type="text" id="materType" name="materType"></input>-->     
		                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		                    <input type="button" onclick="searchInfo()" value="查询">					 
						
						</div>
					</form>
				</div>
		</td>
		</tr>
           </table>
		<table width="98%">
		<tr style="height: 12px;"></tr>
		<tr>
		<td>
			<table id="listDisplay" title="库存材料列表" 
			iconCls="icon-list" singleSelect="false" idField="sid"
			url="<c:url value="/store/findSelectStoreMater.do"/>" loadMsg="请稍候......"
			pagination="true" pageSize="20"
			pageList="[10,20,30,40,50,100]" sortName="sid"
			rownumbers="true" sortOrder="asc">
			<thead>
				<tr>
				    <th field="materRole" width="25" align="center"  checkbox="true">
					</th> 
					<th field="sid" width="80" sortable="true" hidden="true">
						ID
					</th>
				    <th field="materId" width="80" sortable="true" >
						材料ID
					</th>	
 					<th field="materName" width="80"  sortable="true" >
						材料名
					</th>		
					<th field="materType" width="100" formatter="formatFoodType1" sortable="true" >
						种类
					</th>	
                    <th field="brands" width="100" sortable="true" >品牌
                    </th>  
                    <th field="specifications" width="100" sortable="true" >规格
                    </th>   
                    <th field="unit" width="50" sortable="true" >单位
                    </th>
					<th field="materNum" width="150" sortable="true" align="center"  >
						库存数量
					</th>
					<th field="materNumOut" width="150" sortable="true" editor="text" align="center"  >
						出库数量
					</th>
 				</tr>
			</thead>
			</table>
			</td>
			</tr>
			<tr>
            <td>
            <table id="listDisplay2" title="已选出库单" 
                iconCls="icon-list" singleSelect="false" idField="sid"
                loadMsg="请稍候......"
                pagination="true" pageSize="20"
                pageList="[10,20,30,40,50,100]" sortName="sid"
                rownumbers="true" sortOrder="asc">
            <thead>
                <tr>
                    <th field="materRole" width="25" align="center"  checkbox="true">
                    </th> 
                    <th field="sid" width="80" sortable="true" hidden="true">ID
                    </th>
                    <th field="materId" width="80" sortable="true" >材料ID
                    </th>   
                    <th field="materName" width="80"  sortable="true" >材料名
                    </th>       
                    <th field="materType" width="100" formatter="formatFoodType1" sortable="true" >种类
                    </th>   
                    <th field="brands" width="100" sortable="true" >品牌
                    </th>  
                    <th field="specifications" width="100" sortable="true" >规格
                    </th>   
                    <th field="unit" width="50" sortable="true" >单位
                    </th>
                    <th field="materNum" width="150" sortable="true" align="center"  >库存数量
                    </th>
                    <th field="materNumOut" width="150" sortable="true" align="center"  >出库数量
                    </th>
                </tr>
            </thead>
            </table>
            </td>
            </tr>
		</table>
	</body>
</html>